/**
 * 1、挂载插件
 * 2、重写push方法
 * 3、实例化，配置路由
 * 4、实现路由权限拦截
 */
import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'

Vue.use(Router)

const pushPlugin = Router.prototype.push
Router.prototype.push = function(params) {
    pushPlugin.call(this, params).catch(() => {})
}

/** 解决首次加载慢的问题 */
const NotRight = () => import('../pages/common/NotRight')

const Login = () => import('../pages/login')
const container = () => import('../pages/common/Container.vue')
const Not = () => import('../pages/common/NotFind.vue')
// const A = () => import('../pages/system/menu/index.vue')

// const Login = () => import('../pages/myLogin.vue')

// const Home = () => import('../pages/home')
// const UserList = () => import('../pages/user/list')
// const UserEdit = () => import('../pages/user/edit')

const router = new Router({
    mode: 'history',
    routes: [
        {path: '/', redirect: '/login'},
        {path: '/login', name:'login', component: Login, meta: {noLogin: true}},
        
        {path:'/sys',name:'a', component:container,
            children:[
                {path: '/403', component: NotRight, meta: {noLogin: true}},
            ]
        },
        // {path:'/a',component:A},
        // {path: '/home', component: Home},
        {path: '*', component: Not}
    ]
})

router.beforeEach(function(to, _, next) {
    /**
     * 1、是否需要拦截
     * 2、获取标识--vuex中
     * 3、判断是否符合条件：token登录标识，用户访问权限
     */
    if (to.meta.noLogin) {
        next()
        return
    }

    let _token = store.getters['common/token']
    if (!_token) {
        next('/login')
        return
    }

    // 判断访问权限
    let r = store.getters['common/userEole']
    

    let menuList = store.getters['common/menuList']
    let _path = to.path.slice(4) 

    menuList.forEach(it => {
        // 找到当前路径
        if(it.path === _path){
            // 判断是否需要权限
            if(it.path_right){
                // 获取用户当前权限
                let a = r[it.parent_id] || r[it.id]
                // 判断权限是否通过
                // || it.path === '/product/list' || it.path === '/product/edit' || it.path === '/product/sampleList' || it.path === '/product/sampleEdit' || it.path === '/product/giftEdit' || it.path === '/product/giftList'
                console.log(r);
                if(a?.includes(it.path_right)){
                    next()
                    return
                }else{
                    next('/403')
                    return
                }
            }

        }
    });

    next()
})

export default router